const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  console.log('设置代理中间件...');
  
  // 创建代理中间件
  const userApiProxy = createProxyMiddleware({
    target: 'http://192.168.2.141:8083',
    changeOrigin: true,
    secure: false,
    logLevel: 'debug',
    pathRewrite: path => path,
    onProxyReq: (proxyReq, req, res) => {
      console.log(`[代理请求] ${req.method} ${req.url} -> http://192.168.2.141:8083${proxyReq.path}`);
      
      // 修改Origin头以匹配目标服务器
      proxyReq.setHeader('Origin', 'http://192.168.2.141:8083');
      
      // 如果是POST请求且有请求体，需要特殊处理
      if (req.body && req.method === 'POST') {
        try {
          const bodyData = JSON.stringify(req.body);
          // 更新Content-Length
          proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
          // 写入请求体
          proxyReq.write(bodyData);
          console.log('请求体已处理:', bodyData);
        } catch (error) {
          console.error('处理请求体时出错:', error);
        }
      }
    },
    onProxyRes: (proxyRes, req, res) => {
      console.log(`[代理响应] ${req.method} ${req.url} -> ${proxyRes.statusCode}`);
      
      // 添加CORS头
      proxyRes.headers['Access-Control-Allow-Origin'] = '*';
      proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
      proxyRes.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
      proxyRes.headers['Access-Control-Allow-Credentials'] = 'true';
    },
    onError: (err, req, res) => {
      console.error('[代理错误]', err);
      res.writeHead(500, {
        'Content-Type': 'text/plain',
      });
      res.end(`代理请求错误: ${err.message}`);
    }
  });
  
  const projectApiProxy = createProxyMiddleware({
    target: 'http://192.168.2.141:9200',
    changeOrigin: true,
    secure: false,
    logLevel: 'debug',
    pathRewrite: path => path,
    onProxyReq: (proxyReq, req, res) => {
      console.log(`[代理请求] ${req.method} ${req.url} -> http://192.168.2.141:9200${proxyReq.path}`);
      
      // 修改Origin头以匹配目标服务器
      proxyReq.setHeader('Origin', 'http://192.168.2.141:9200');
      
      // 如果是POST请求且有请求体，需要特殊处理
      if (req.body && req.method === 'POST') {
        try {
          const bodyData = JSON.stringify(req.body);
          // 更新Content-Length
          proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
          // 写入请求体
          proxyReq.write(bodyData);
          console.log('请求体已处理:', bodyData);
        } catch (error) {
          console.error('处理请求体时出错:', error);
        }
      }
    }
  });
  
  // 应用代理到所有路径
  app.use('/user', userApiProxy);
  app.use('/api/project', projectApiProxy);
  app.use('/project', projectApiProxy);
  app.use('/api/task', projectApiProxy);
  app.use('/api', userApiProxy);
  
  // 处理OPTIONS预检请求
  app.options('*', (req, res) => {
    console.log('处理OPTIONS预检请求:', req.url);
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    res.header('Access-Control-Allow-Credentials', 'true');
    res.sendStatus(200);
  });
  
  console.log('代理中间件设置完成');
};
